package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CollectRemoveBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.TestCollectBean;
import cn.bocweb.spinning.model.Bean.TestKeysBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.CheckAnswerAdapter;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.fragment.CheckAnswerFragment;
import de.greenrobot.event.EventBus;

public class CheckAnswerActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.viewPager_check_answer)
    ViewPager viewPagerCheckAnswer;
    @Bind(R.id.test_btn_test_list)
    LinearLayout testBtnTestList;
    @Bind(R.id.train_main)
    LinearLayout trainMain;

    String libid;
    boolean collected;

    CheckAnswerAdapter adapter;
    PopupWindow popupWindow;
    TestListAdapter testListAdapter;
    Map<Integer, Boolean> testlist;
    String checkAnswerTestid, checkErrorTestid;
    List<Fragment> fragments;
    UserPresenter presenter;
    Integer sizeInt;
    int size, right, wrong;
    @Bind(R.id.check_answer_num)
    TextView checkAnswerNum;
    @Bind(R.id.check_answer_count)
    TextView checkAnswerCount;
    @Bind(R.id.check_answer_collect)
    LinearLayout checkAnswerCollect;
    List<TestKeysBean.DataEntity> testInfo;
    TextView checkAnswerRight;
    TextView checkAnswerWrong;
    TextView checkAnswerMiss;
    @Bind(R.id.imageview_collect)
    ImageView imageviewCollect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_answer);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initToolbar();
        initClickBtn();
        initPopupWindow();
        initViewPager();
        initIntent();
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent.getBooleanExtra(Constant.CHECK_COLLECT_DELETE, false)) {
            checkAnswerCollect.setVisibility(View.GONE);
        } else {
            checkAnswerCollect.setVisibility(View.VISIBLE);
        }
        checkAnswerTestid = intent.getStringExtra(Constant.CHECK_ANSWER_TESTID);
        checkErrorTestid = intent.getStringExtra(Constant.CHECK_ERROR_TESTID);
        libid = intent.getStringExtra(Constant.CHECK_ANSWER_LIBID);
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        presenter = new UserPresenterImp();
        if (!TextUtils.isEmpty(checkAnswerTestid)) {
            presenter.testKeys(dataEntity.getUserid(), checkAnswerTestid);
        }
        if (!TextUtils.isEmpty(checkErrorTestid)) {
            presenter.testError(dataEntity.getUserid(), checkErrorTestid);
        }
        testInfo = new ArrayList<>();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initPopupWindow() {
        testlist = new HashMap<>();
        testListAdapter = new TestListAdapter(this, size, testlist, false);

        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        GridView gridView_testList = (GridView) view.findViewById(R.id.test_list);
        RelativeLayout btn_hide = (RelativeLayout) view.findViewById(R.id.btn_hide);

        checkAnswerRight = (TextView) view.findViewById(R.id.exam_popup_right);
        checkAnswerWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        checkAnswerMiss = (TextView) view.findViewById(R.id.exam_popup_miss);

        btn_hide.setOnClickListener(this);
        gridView_testList.setAdapter(testListAdapter);

        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        int toolbarHeight = DeviceUtil.getViewHeight(toolbar);

        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {

            @Override
            public void click(int position) {
                popupWindow.dismiss();
                viewPagerCheckAnswer.setCurrentItem(position);
            }
        });

        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, screenHeightPx - toolbarHeight - navigationHeight);
        popupWindow.setAnimationStyle(R.style.test_list);
    }

    private void initClickBtn() {
        testBtnTestList.setOnClickListener(this);
        checkAnswerCollect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.test_btn_test_list: {
                popupWindow.showAtLocation(trainMain, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.btn_hide: {
                popupWindow.dismiss();
                break;
            }
            case R.id.check_answer_collect: {
                LibListBean.DataEntity data = new LibListBean.DataEntity();
                data.readLibListIntoLocal(this);
                UserBean.DataEntity user = new UserBean.DataEntity();
                user.readInfoFromLocal(this);
                String testId = String.valueOf(testInfo.get(viewPagerCheckAnswer.getCurrentItem()).getId());
                String ttype = String.valueOf(testInfo.get(viewPagerCheckAnswer.getCurrentItem()).getTtype());
                String isright = String.valueOf(testInfo.get(viewPagerCheckAnswer.getCurrentItem()).getIsright());
                String choose = String.valueOf(testInfo.get(viewPagerCheckAnswer.getCurrentItem()).getChoose());
                if (collected) {
                    String libidS = TextUtils.isEmpty(libid) ? data.getId() : libid;
                    presenter.collectRemove(libidS, user.getUserid(), "2", testId, ttype);
                } else {
                    String libidS = TextUtils.isEmpty(libid) ? data.getId() : libid;
                    presenter.testCollect(testId, ttype, libidS, user.getUserid(), isright, choose);
                }
            }
        }
    }

    public void onEventMainThread(CollectRemoveBean bean) {
        if (bean.getReturn_code() == 0) {
            imageviewCollect.setImageResource(R.mipmap.train_collect);
            collected = false;
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    private void initViewPager() {
        fragments = new ArrayList<>();
        adapter = new CheckAnswerAdapter(getSupportFragmentManager(), fragments);
        viewPagerCheckAnswer.setAdapter(adapter);
        viewPagerCheckAnswer.setPageTransformer(true, new ZoomOutPageTransformer());
        viewPagerCheckAnswer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                checkAnswerNum.setText(String.valueOf(position + 1));
                String isCollect = testInfo.get(position).getIsCollect();
                if (isCollect.equals("1")) {
                    collected = true;
                    imageviewCollect.setImageResource(R.mipmap.collected);
                } else if (isCollect.equals("0")){
                    collected = false;
                    imageviewCollect.setImageResource(R.mipmap.train_collect);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void onEventMainThread(TestKeysBean bean) {
        if (bean.getReturn_code() == 0) {
            if (bean.getData() == null || bean.getData().isEmpty()) {
                DeviceUtil.MyToast(this, "题目已经被删除");
                finish();
                return;
            }
            if (bean.getData().get(0).getIsCollect().equals("1")) {
                collected = true;
                imageviewCollect.setImageResource(R.mipmap.collected);
            } else {
                collected =false;
                imageviewCollect.setImageResource(R.mipmap.train_collect);
            }
            testInfo.addAll(bean.getData());
            checkAnswerCount.setText(String.valueOf(bean.getData().size()));
            for (int i = 0; i < bean.getData().size(); i++) {
                fragments.add(new CheckAnswerFragment(bean.getData(), i));
                switch (Integer.parseInt(bean.getData().get(i).getIsright())) {
                    case 0: {
                        DeviceUtil.Log("false");
                        testlist.put(i, false);
                        wrong++;
                        break;
                    }
                    case 1: {
                        DeviceUtil.Log("true");
                        testlist.put(i, true);
                        right++;
                        break;
                    }
                }
            }

            adapter.notifyDataSetChanged();
            testListAdapter.setSize(bean.getData().size());
            testListAdapter.notifyDataSetChanged();
            checkAnswerRight.setText(String.valueOf(right));
            checkAnswerWrong.setText(String.valueOf(wrong));
            checkAnswerMiss.setText(String.valueOf(bean.getData().size() - right - wrong));
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(TestCollectBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            collected = true;
            imageviewCollect.setImageResource(R.mipmap.collected);
            testInfo.get(viewPagerCheckAnswer.getCurrentItem()).setIsCollect("1");
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }
}
